<?php

	class TcpClient
	{
		public $cli;
		public $ip;
		public $port;
		public function __construct($ip='127.0.0.1',$port=3000)
		{
			$this->ip = $ip;
			$this->port = $port;
			$this->cli = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
			$this->listen();
			$this->cli->connect($this->ip,$this->port,0.5);
		}

		public function listen()
		{
			$this->cli->on('connect',[$this,'connect']);
			$this->cli->on('receive',[$this,'receive']);
			$this->cli->on('error',[$this,'error']);
			$this->cli->on('close',[$this,'close']);
		}

		public function receive($cli,$data)
		{
			echo "cli: $data\n";
		}

		public function connect()
		{
			echo "cli: connect\n";
			$this->send('hello');
			swoole_event_add(STDIN,[$this,'input']);
		}

		public function error()
		{

		}

		public function close()
		{
			echo "cli: close\n";
		}

		public function send($data)
		{
			$this->cli->send($data);
		}

		public function input()
		{
			$data = trim(fgets(STDIN));
			if($data=='exit'){
				$this->cli->close();
				exit;
			}
			$this->send($data);
		}
	}

	//new TcpClient;